package model

import (
	"ginTea/structs"
	"ginTea/utils/errmsg"
	"ginTea/utils/helpers"
	"strconv"
	"time"
)

type Orders struct {
	ID        uint      `gorm:"primary_key" json:"id"`
	CreatedAt time.Time `json:"created_at" gorm:"column:created_at;autoCreateTime"`
	Year      int       `gorm:"year" json:"year"`
	Month     int       `gorm:"month" json:"month"`
	Day       int       `gorm:"day" json:"day"`
	UpdatedAt time.Time `json:"updated_at" gorm:"column:updated_at;autoCreateTime"`
	UserId    int       `gorm:"not null" json:"user_id"`
	UserInfo  User      `gorm:"foreignkey:UserId" json:"user_info"`
	GoodsInfo Goods     `gorm:"foreignkey:GoodsId" json:"goods_info"`
	GoodsId   int       `gorm:"not null" json:"goods_id"`
	Status    string    `gorm:"not null" json:"status"`
	OrderUid  string    `gorm:"not null" json:"order_uid"`
	Count     int       `gorm:"not null" json:"count"`
	PayAmount int       `gorm:"not null" json:"pay_amount"`
}

// 新增订单
func CreateOrders(data *Orders) int {
	getYear := time.Now().Format("2006") //获取年
	getMonth := time.Now().Format("01")  //获取月
	getDay := time.Now().Format("02")    //获取日
	intYear, _ := strconv.Atoi(getYear)
	intMonth, _ := strconv.Atoi(getMonth)
	intDay, _ := strconv.Atoi(getDay)
	data.Year = intYear
	data.Month = intMonth
	data.Day = intDay
	err := db.Create(&data).Error
	if err != nil {
		return errmsg.ERROR
	} else {
		return errmsg.SUCCESS
	}
}

/*
获取所有商品
pageNum 当前页号
pageSize当前页大小
*/
func GetOrdersList(page int, pageSize int, keyword string, user_id int, year int) structs.JSONResponse {
	// var goodsList []Goods
	var order []Orders
	var total int
	var list []interface{}
	tx := db.Model(&order).Where("ID >0")
	if len(keyword) > 0 {
		tx = tx.Where("id LIKE ?", "%"+keyword+"%")
	}
	if year > 0 {
		tx = tx.Where("year =?", year)
	}
	if user_id > 0 {
		tx = tx.Where("user_id = ?", user_id)
	}
	tx = tx.Preload("UserInfo")
	tx = tx.Preload("GoodsInfo")
	tx.Count(&total)
	err := tx.Order("id desc").
		Limit(pageSize).
		Offset((page - 1) * pageSize).
		Find(&order).
		RecordNotFound()
	if err {
		return helpers.Error("")
	}
	for _, v := range order {
		list = append(list, v)
	}
	pageData := structs.NewPageData(list, pageSize, page, total)
	response := helpers.Success(pageData)
	return response
}

// 更新订单
func UpdateOrderStatus(id int, data *Orders) int {
	var order Orders
	var maps = make(map[string]interface{})
	maps["status"] = data.Status
	err := db.Model(&order).Where("id = ?", id).Updates(maps).Error
	if err != nil {
		return errmsg.ERROR
	}
	return errmsg.SUCCESS
}
